import getTempId from "@/utils/utilTempId";
import {reqLogin, reqLogout, reqUserInfo} from "@/api";
const state ={
    userTempId : getTempId(),
    token:localStorage.getItem("token")||"",
    userInfo:{
        nickName:""
    }
};
const mutations={
    SET_TOKEN_STATE(state,payload){
        state.token = payload.token
    },
    SET_USERINFO_STATE(state,payload){
        state.userInfo = payload.userInfo
    },
    REMOVE_STATE(state){
        state.token = "";
        state.userInfo={nickName:""};
        localStorage.removeItem("token")
    }
}
const actions = {
    async getToken({commit},userInfo){
        const result =  await reqLogin(userInfo)
        localStorage.setItem("token",result.token)
        commit("SET_TOKEN_STATE",{token:result.token})
    },
    async getUserInfo({commit}){
        const result = await  reqUserInfo()
        commit("SET_USERINFO_STATE",{userInfo:result})
    },
     getRemove({commit}){
       commit("REMOVE_STATE")
    },
    async getLogOut({commit}){
        try {
            await reqLogout()
            commit("REMOVE_STATE")
        }catch (e){
            return Promise.reject(e)
        }
    }
}

export default {
    namespaced:true,
    state,
    mutations,
    actions
}